package com.youlai.boot.modules.game.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.modules.game.mapper.GameCommentLikeMapper;
import com.youlai.boot.modules.game.mapper.GameCommentMapper;
import com.youlai.boot.modules.game.mapper.GameInfoMapper;
import com.youlai.boot.modules.game.model.entity.GameComment;
import com.youlai.boot.modules.game.model.entity.GameCommentLike;
import com.youlai.boot.modules.game.model.form.GameCommentForm;
import com.youlai.boot.modules.game.model.query.GameCommentQuery;
import com.youlai.boot.modules.game.model.vo.GameCommentVO;
import com.youlai.boot.modules.game.service.GameCommentService;
import com.youlai.boot.modules.game.service.GameInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 游戏评论服务实现类
 *
 * @author 有来技术团队
 */
@Service
@RequiredArgsConstructor
public class GameCommentServiceImpl extends ServiceImpl<GameCommentMapper, GameComment> implements GameCommentService {

    private final GameCommentMapper gameCommentMapper;
    private final GameCommentLikeMapper gameCommentLikeMapper;
    private final GameInfoMapper gameInfoMapper;
    private final GameInfoService gameInfoService;

    @Override
    public Page<GameCommentVO> getCommentPage(GameCommentQuery queryParams) {
        // 设置当前用户ID，用于查询点赞状态
        Long userId = SecurityUtils.getUserId();
        queryParams.setUserId(userId);

        Page<GameComment> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        Page<GameCommentVO> commentPage = gameCommentMapper.getCommentPage(page, queryParams);

        // 如果是查询一级评论，获取其子评论
        if (queryParams.getRootOnly() != null && queryParams.getRootOnly() && commentPage.getRecords().size() > 0) {
            for (GameCommentVO comment : commentPage.getRecords()) {
                List<GameCommentVO> children = gameCommentMapper.getChildComments(comment.getId(), userId);
                comment.setChildren(children);
            }
        }

        return commentPage;
    }

    @Override
    public GameCommentVO getCommentDetail(Long id) {
        Long userId = SecurityUtils.getUserId();
        GameCommentVO comment = gameCommentMapper.getCommentById(id, userId);

        if (comment != null && comment.getParentId() == null) {
            // 获取子评论
            List<GameCommentVO> children = gameCommentMapper.getChildComments(id, userId);
            comment.setChildren(children);
        }

        return comment;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long addComment(GameCommentForm formData) {
        Long userId = SecurityUtils.getUserId();

        GameComment entity = new GameComment();
        entity.setGameId(formData.getGameId());
        entity.setUserId(userId);
        entity.setContent(formData.getContent());
        entity.setRating(formData.getRating());
        entity.setParentId(formData.getParentId());
        entity.setReplyUserId(formData.getReplyUserId());
        entity.setLikeCount(0);
        entity.setStatus(1); // 默认已发布

        save(entity);

        // 如果是对游戏的评分，更新游戏评分
        if (formData.getRating() != null && formData.getParentId() == null) {
            gameInfoService.updateRating(formData.getGameId(), formData.getRating().doubleValue());
        }

        return entity.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateComment(Long id, GameCommentForm formData) {
        Long userId = SecurityUtils.getUserId();

        GameComment entity = getById(id);
        if (entity == null || !entity.getUserId().equals(userId)) {
            return false;
        }

        entity.setContent(formData.getContent());
        if (formData.getRating() != null) {
            entity.setRating(formData.getRating());
        }

        boolean updated = updateById(entity);

        // 如果是对游戏的评分，更新游戏评分
        if (updated && formData.getRating() != null && entity.getParentId() == null) {
            gameInfoService.updateRating(entity.getGameId(), formData.getRating().doubleValue());
        }

        return updated;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteComment(Long id) {
        Long userId = SecurityUtils.getUserId();

        GameComment entity = getById(id);
        if (entity == null || !entity.getUserId().equals(userId)) {
            return false;
        }

        // 删除子评论
        if (entity.getParentId() == null) {
            LambdaQueryWrapper<GameComment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GameComment::getParentId, id);
            remove(queryWrapper);
        }

        // 删除点赞记录
        LambdaQueryWrapper<GameCommentLike> likeQueryWrapper = new LambdaQueryWrapper<>();
        likeQueryWrapper.eq(GameCommentLike::getCommentId, id);
        gameCommentLikeMapper.delete(likeQueryWrapper);

        return removeById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean toggleLike(Long id) {
        Long userId = SecurityUtils.getUserId();

        // 检查评论是否存在
        GameComment comment = getById(id);
        if (comment == null) {
            return false;
        }

        // 检查用户是否已点赞
        int likeCount = gameCommentLikeMapper.checkUserLiked(id, userId);
        
        if (likeCount > 0) {
            // 已点赞，取消点赞
            LambdaQueryWrapper<GameCommentLike> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GameCommentLike::getCommentId, id)
                    .eq(GameCommentLike::getUserId, userId);
            gameCommentLikeMapper.delete(queryWrapper);
            
            // 减少点赞数
            gameCommentMapper.decrementLikeCount(id);
            
            return true;
        } else {
            // 未点赞，添加点赞
            GameCommentLike like = new GameCommentLike();
            like.setCommentId(id);
            like.setUserId(userId);
            gameCommentLikeMapper.insert(like);
            
            // 增加点赞数
            gameCommentMapper.incrementLikeCount(id);
            
            return true;
        }
    }
} 